package org.pupil.rpc.router.routerImpl;

import org.pupil.rpc.common.ServiceMeta;
import org.pupil.rpc.config.RpcProperties;
import org.pupil.rpc.registry.RegistryService;
import org.pupil.rpc.router.LoadBalancer;
import org.pupil.rpc.router.ServiceMetaRes;
import org.pupil.rpc.spi.ExtensionLoader;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 负载均衡算法——轮询算法
 */
public class RoundRobinLoadBalancer implements LoadBalancer {

    // 原子计数器
    private static AtomicInteger roundRobinId = new AtomicInteger(0);

    @Override
    public ServiceMetaRes select(Object[] params, String serviceName) {
        // 获取注册中心
        RegistryService registryService = ExtensionLoader.getInstance().get(RpcProperties.getInstance().getRegisterType());

        // 获取所有服务
        List<ServiceMeta> discoveries = registryService.discoveries(serviceName);

        // 获取服务器长度
        int size = discoveries.size();

        // 计数器加一
        roundRobinId.addAndGet(1);
        // 当计数器等于int类型最大值时重设为0
        if (roundRobinId.get() == Integer.MAX_VALUE){
            roundRobinId.set(0);
        }

        // 根据当前轮询ID取余服务长度得到具体服务
        return ServiceMetaRes.build(discoveries.get(roundRobinId.get()%size),discoveries);
    }
}
